#include "../entity/AccountPOJO.hpp"
#include "SqliteUtils.h"
#include "../common/SqlUtils.hpp"
#include "../common/StringUtils.hpp"
#include "./AccountDao.h"




extern SqliteUtils g_db;
class AccountDaoImpl : public AccountDao
{

	public:
		 AccountPOJO   getByUserName(const string& username) override  {
			std::vector<std::string> arrKey(10);
			vector<vector<string>> arrValue(10);
			g_db.FindAllData("SELECT id,username,password,balance from t_user WHERE username='"+username+"'", arrKey, arrValue);
			AccountPOJO AccountPOJO;
			if (arrValue.size() == 1) {
				AccountPOJO.id = stoi(arrValue[0][0]);
				AccountPOJO.username = arrValue[0][1];
				AccountPOJO.password = arrValue[0][2];
				AccountPOJO.balance = stoi(arrValue[0][3]);
				return AccountPOJO;
			}
			return AccountPOJO;
		}

		AccountPOJO  getByUserId(const uint32_t id) override {
			std::vector<std::string> arrKey(10);
			vector<vector<string>> arrValue(10);
			g_db.FindAllData("SELECT id,username,password,balance from t_user WHERE id=" + std::to_string(id) , arrKey, arrValue);
			AccountPOJO AccountPOJO;
			if (arrValue.size() == 1) {
				AccountPOJO.id = stoi(arrValue[0][0]);
				AccountPOJO.username = arrValue[0][1];
				AccountPOJO.password = arrValue[0][2];
				AccountPOJO.balance = stoi(arrValue[0][3]);
				return AccountPOJO;
			}
			return AccountPOJO;
		}

	
		vector<AccountPOJO>  listAll(const AccountQuery & accountQuery) override {
			std::vector<std::string> arrKey(10);
			vector<vector<string>> arrValue(10);
			vector<AccountPOJO> userList = vector<AccountPOJO>();
			string sql = "SELECT id, username, password, balance from t_user where 1=1 ";
			if (!StringUtils::isEmpty(accountQuery.username)) {
				sql = SqlUtils::appendEqCase(sql, "username", accountQuery.username);
			}
			g_db.FindAllData(sql, arrKey, arrValue);
			if (arrValue.size() >0) {
				for (int i = 0; i < arrValue.size(); i++)
				{
					AccountPOJO AccountPOJO ;
					AccountPOJO.id = stoi(arrValue[i][0]);
					AccountPOJO.username = arrValue[i][1];
					AccountPOJO.password = arrValue[i][2];
					AccountPOJO.balance = stoi(arrValue[i][3]);
					userList.push_back(AccountPOJO);
				}
			}
			return userList;
		}

	     uint32_t  inster(const AccountPOJO& AccountPOJO)  override {
			char sql_char[1024] = { 0 };
			sprintf_s(sql_char, "INSERT INTO t_user( username, password, balance) VALUES ( '%s', '%s', 0)", AccountPOJO.username.c_str(), AccountPOJO.password.c_str());
			uint32_t r= g_db.Insert(sql_char);
			return r;
		}


		uint32_t  update(const AccountPOJO& AccountPOJO) override {
			char sql_char[1024] = { 0 };
			sprintf_s(sql_char, "UPDATE t_user SET balance = %d WHERE id =  %d", AccountPOJO.balance, AccountPOJO.id);
			uint32_t r = g_db.Update(sql_char);
			return r;
		}

		uint32_t  getTotalMoney()  override {
		    string r= g_db.FindSingleVal("SELECT sum(balance) c from t_user");
		    uint32_t totalMoney = atoi(r.c_str());
			return totalMoney;
		}

};
